<?php

namespace app\admin\model\template;

use app\admin\model\Node;
use app\admin\model\NodeDetail;
use app\admin\model\User;
use think\Model;

/**
 * 模板模型类
 */
class Review extends Model
{

    // 定义关联的数据表名称
    protected $name = 'template_review';
    // 开启自动时间戳字段
    protected $autoWriteTimestamp = 'integer';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    protected $type = [
        'snapshot' => 'array',
        'images' => 'array',
        'node_detail' => 'array',
        'createtime' => 'timestamp:Y-m-d H:i:s',
        'checktime' => 'timestamp:Y-m-d H:i:s'
    ];

    public function getTemplateSn(): string
    {
        $no_use = true;
        $sn = '';
        while ($no_use) {
            $sn = get_random_str(3, 14);
            if (!$this->where('sn', $sn)->find()) {
                $no_use = false;
            }
        }
        return $sn;
    }

    public function getTemplateNodeByProductId(int $product_id)
    {
        return Node::where('product_id', $product_id)
            ->field('id,pid,name,level,path,is_factor,factor_id,is_template,template_id,node_type')
            ->select();
    }

    public function getTemplateNodeDetailByProductId(int $product_id)
    {
        return NodeDetail::where('product_id', $product_id)
            ->field('id,node_id,io_type_id,io_category_id,type')
            ->select();
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function template()
    {
        return $this->hasOne(Template::class, 'id', 'template_id');
    }

    public function product()
    {
        return $this->hasOne(Product::class, 'id', 'product_id');
    }
    public function groupInfo()
    {
        return $this->hasOne(TemplateCategory::class, 'id', 'group_id');
    }

    public function category()
    {
        return $this->hasOne(TemplateCategory::class, 'id', 'category_id');
    }

    public function getGroupNameAttr()
    {
        return $this->groupInfo()->value('name');
    }

    public function getCategoryNameAttr()
    {
        return $this->category()->value('name');
    }


    public function getStatusList()
    {
        return ['0' => '待审','1' => '已通过','2' => '驳回'];
    }
}